﻿using DesertKharonIrcPlugin.Properties;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;

namespace DesertKharonIrcPlugin.GdiPlusRendering
{
    // TODO: Change this class to be flexible ... ... maybe.
    public class LoadingAnimation : IDisposable
    {
        private List<Bitmap> _bitmapList = new List<Bitmap>();
        private float _secondsPerFrame = 0.05f;
        private int _currentFrame = 0;

        public int CurrentFrame
        {
            get { return _currentFrame; }
        }

        public float SecondsPerFrame
        {
            get { return _secondsPerFrame; }
            set { _secondsPerFrame = Math.Max(0.01f, Math.Min(1f, value)); }
        }

        public Bitmap Bitmap
        {
            get { return _bitmapList[_currentFrame]; }
        }

        public LoadingAnimation(float scale)
        {
            int scaledWidthAndHeight = (int)Math.Ceiling(26f * scale);

            // split the loading graphic ...
            Bitmap loadingBitmap = Resources.loading26x26;
            Rectangle destinationRect = new Rectangle(0, 0, scaledWidthAndHeight, scaledWidthAndHeight);
            for (int i = 0; i < 19; i++)
            {
                Rectangle sourceRect = new Rectangle(0, i * 26, 26, 26);

                Bitmap bitmap = new Bitmap(scaledWidthAndHeight, scaledWidthAndHeight);
                using (Graphics graphics = Graphics.FromImage(bitmap))
                {
                    graphics.InterpolationMode = InterpolationMode.High;
                    graphics.CompositingQuality = CompositingQuality.HighQuality;
                    graphics.SmoothingMode = SmoothingMode.AntiAlias;

                    graphics.DrawImage(loadingBitmap, destinationRect, sourceRect, GraphicsUnit.Pixel);
                }

                _bitmapList.Add(bitmap);
            }
        }

        private double _totalElapsedSeconds = 0f;
        public void Update(float elapsedSeconds)
        {
            _totalElapsedSeconds += elapsedSeconds;
            while (_totalElapsedSeconds > _secondsPerFrame)
            {
                _currentFrame += 1;
                _totalElapsedSeconds -= _secondsPerFrame;
            }

            _currentFrame %= _bitmapList.Count;
        }

        public void Dispose()
        {
            if (_bitmapList != null)
            {
                for (int i = 0; i < _bitmapList.Count; i++)
                    _bitmapList[i].Dispose();

                _bitmapList.Clear();
                _bitmapList = null;
            }
        }
    }
}
